

<div class="easyui-layout" data-options="fit:true">
	<div data-options="region: 'west', title: '待选权限', border: false, split: false" style="width: 550px;border-left:0px;border-bottom:0px;">
		<div id="tg">
			<div id="toolbars-resource" style="display:none;">
				<form id="searchForm">
					<div class="datagrid-toolbars">
						<div class="toolbar-row">
							<div class="group">
								<a onclick="reload();" href="javascript:;" class="bto bto-purple1"><i class="fa fa-refresh"></i><span>刷新</span></a>
							</div>
							<div class="group">
								<input id="menu" class="easyui-validatebox" type="text" style="width: 150px; height: 25px;" />
							</div>
						</div>
					</div>
				</form>
			</div>
		</div>
    </div>
    <div data-options="region: 'center'" style="border-bottom:0px;border-top:0px;">
		<ul class="left-right-all">
			<li><a href="javascript:chooseAll();"><i class="fa fa-fast-forward"></i></a></li>
			<li><a href="javascript:chooseMore();"><i class="fa fa-step-forward"></i></a></li>
			<li><a href="javascript:deleteRows();"><i class="fa fa-step-backward"></i></a></li>
			<li><a href="javascript:deleteAllRow();"><i class="fa fa-fast-backward"></i></a></li>
		</ul>
    </div>
    <div data-options="region: 'east', title: '已选权限', border: false, split: false" style="width: 420px;border-right:0px;border-bottom:0px;">
		<div id="swich_dg">
			<div id="swich_toolbars" style="display:none;">
				<form id="searchForm">
					<div class="datagrid-toolbars">
						<div class="toolbar-row">
							<div class="group">
								<a onclick="" href="javascript:add();" class="bto bto-green"><i class="fa fa-plus"></i><span>新增</span></a>
								<a onclick="" href="javascript:;" class="bto bto-blue"><i class="fa fa-pencil"></i><span>编辑</span></a>
							</div>
						</div>
					</div>
				</form>
			</div>
		</div>
    </div>

</div>


<script>
var $tg, $menu, $swich_dg ;
$(function(){
	loadResource();
	loadMenu();
	swich_dg();
	loadRolePermit();
});

function loadMenu() {
	$menu = $("#menu").combobox({
		url: "${ctx}/manager/system/menu/getAllList",
		valueField: "id", panelHeight: 180,
		onSelect: function(record) {
			$tg.treegrid({url: "${ctx}/manager/system/resource/treegridByMenuLinkPermit/"+record.id}) ;
		},
		onLoadSuccess: function() {
			var data= $menu.combobox("getData") ;
			if(data.length > 0) {
				$menu.combobox("setValue", data[0].id);
				$tg.treegrid({url: "${ctx}/manager/system/resource/treegridByMenuLinkPermit/"+data[0].id}) ;
			} else {
				$(".bto").attr("onclick", "").click(function(){
					alertify.warning("目前没有菜单，请先创建菜单！");
				}); ;
			}
		}
	});
}

function loadResource() {
	$tg = $("#tg").treegrid({
        idField: "id", treeField: "text", fit: true, 
        border: false, striped:true, singleSelect: false, rownumbers: true, autoRowHeight: true, fitClomuns: true,
        toolbar: "#toolbars-resource", sortName: 'sorting', sortOrder: 'asc', queryParams: {},
        frozenColumns: [[
            { field: "id", title: "ID", width: 50, sortable: true, hidden: true } 
        ]],
        columns: [[
            { field: "text", title: "资源名称", width: 150 },
            { field: "permits", title: "权限", formatter:function(value,row){
            	if(undefined != value && value.length > 0){
	            	var op = "<div id='icheck' class='icheck_in' resourceId='res-"+row.id+"'>" ;
	            	$.each(value, function(i, p){
	            		op += "<input id='"+row.id+p.id+"' type='checkbox' permitId='"+p.id+"' name='"+p.name+"' identity='"+p.identity+"'>";
	            		op += "<div class='opts'><label for='"+row.id+p.id+"'>"+p.name+"</label></div>";
	            		
	            	});
	            	op + "</div>" ;
	            	return op;
            	}
            	return "";
            }}
        ]],
        onLoadSuccess: function(){
        	$.fn.treegrid.extensions.onLoadSuccess.apply(this, arguments);
        	$tg.treegrid('unselectAll');$tg.treegrid('clearSelections');
        	$("#icheck input").iCheck({
    			checkboxClass: "icheckbox_minimal-orange"
    	   	});
        },
        enableHeaderClickMenu: true, enableHeaderContextMenu: true, enableRowContextMenu: false
    });
}
function reload(){$tg.treegrid("reload") ;}


function swich_dg() {
	$swich_dg = $("#swich_dg").datagrid({
        idField: "id", fit: true, autoRowHeight: true, fitClomuns: true,
        border: false, striped:true, rownumbers: true, toolbar: "#swich_toolbars", 
        frozenColumns: [[
            { field: "ck", checkbox: true }
        ]],
        columns: [[ 
        	{ field: "id", title: "ID", width: 50, hidden: true },
            { field: "name", title: "资源名称", width: 120 },
            { field: "permits", title: "权限", formatter:function(value,row){
            	return "<div id='subPermitId-"+row.id+"'>"+value+"</div>";
            } },
        ]]
	});
}

//添加行
function appendRow(data) {
	$swich_dg.datagrid('appendRow', data);
}
//修改行
function updateRow(data, permits) {
	var index = $swich_dg.datagrid("getRowIndex", data);
	$swich_dg.datagrid('updateRow', {
		index: index, 
		row: {
			permits: permits
		}
	});
}
//删除多行
function deleteRows() {
	var rows = $swich_dg.datagrid("getSelections"), data = $.array.clone(rows);
    if (!data.length) { $.easyui.messager.show("您未选择任何数据。"); return; }
    $.each(data, function (i, row) { deleteRow(row); });
    $swich_dg.datagrid("unselectAll");
}
//删除所有行
function deleteAllRow() {
	var rows = $swich_dg.datagrid("getRows"), data = $.array.clone(rows);
    if (!data.length) { $.easyui.messager.show("您未选择任何数据。"); return; }
    $.each(data, function (i, row) { deleteRow(row); });
    $swich_dg.datagrid("unselectAll");
}
function deleteRow(row) {
	if (!row) { return; }
    var index = $swich_dg.datagrid("getRowIndex", row);
    if (index > -1) { $swich_dg.datagrid("deleteRow", index); }
}

//添加所有有权限的行
function chooseAll() {
	var roots = $tg.treegrid("getRoots");
	
	var datas = [] ;
	$.each(roots, function(i, p){
		selectChildren(this, p.id, p.text, datas);
	});
	
	var chooseId = [] ;
	var rowsData = [] ;
	var dgRows = $swich_dg.datagrid("getRows");
	$.each(dgRows, function(i, choose_p){
		rowsData.push(choose_p) ;
		chooseId.push(choose_p.id);
	});
	
	$.each(datas, function(i, p){
		if($.array.contains(chooseId, p.id)) {
			$.each(rowsData, function(i, rp){
				if(rp.id == p.id) { //该行已存在，进行修改
					updateRow(rp, p.permits)
				}
			});
			return ;
		} else { //添加新行
			appendRow(p);
		}
	});
}
//递归选择子节点
function selectChildren(target, id, text, datas){
	var children = $tg.treegrid("getChildren", id);
	
	var permits = [];
	var permitsInput = $("div[resourceId=res-"+id+"] >> input") ;
	if(undefined != permitsInput && permitsInput.length > 0) {
		$.each(permitsInput, function(){
			permits.push("<span style='padding: 0 5px;' id='"+$(this).attr("permitid")+"'>"+$(this).attr("name")+"</span>");
		});
		datas.push({id: id, name: text, permits: permits.join(",")});
	}
	
	for(var i=0;i<children.length;i++){
		var childId = children[i]["id"];
		var childText = children[i]["text"];
		selectChildren(target, childId, childText, datas);//递归选择子节点
	}
}

//添加权限行
function chooseMore(){
	var tgRows = $tg.treegrid("getChecked") ;
	if(tgRows.length > 0) {
	
		$.each(tgRows, function(i, p){
			if(p.permits.length > 0) {
				//已勾选的权限
				var checkPermits = $("div[resourceId='res-"+p.id+"'] >> input:checked");
				var permits = [] ;
				if(undefined != checkPermits && checkPermits.length > 0) {
					$.each(checkPermits, function(){
						permits.push("<span style='padding: 0 5px;' id='"+$(this).attr("permitid")+"'>"+$(this).attr("name")+"</span>");
					});
				} else {return false;}
				
				
				var chooseId = [] ;
				var rowsData = [] ;
				var dgRows = $swich_dg.datagrid("getRows");
				$.each(dgRows, function(i, choose_p){
					rowsData.push(choose_p) ;
					chooseId.push(choose_p.id);
				});
				
				if($.array.contains(chooseId, p.id)) {
					$.each(rowsData, function(i, rp){
						if(rp.id == p.id) { //该行已存在，进行修改
							updateRow(rp, permits.join(","))
						}
					});
					return ;
				} else { //添加新行
					appendRow({id: p.id, name: p.text, permits: permits.join(",")});
				}
			}
			
		});
	}
}

//加载该角色已拥有的权限
function loadRolePermit() {
	$.get("${ctx}/manager/system/role/loadRoleByResPermitList/${roleId}", function(result) {
		if(undefined != result && result.length > 0){
			$.each(result, function(i, p) {
				console.info(p);
				var permits = [] ;
				$.each(p.permits, function(i, per) {
					permits.push("<span style='padding: 0 5px;' id='"+per.id+"'>"+per.name+"</span>");
				});
				appendRow({id: p.resource_id, name: p.resource.text, permits: permits.join(",")});
			});
		}
	}, 'json').error(function() { $.easyui.loaded(); });
}

//提交表单数据
var submitNow = function($d, $dg, flag) {
	var dgRows = $swich_dg.datagrid("getRows");
	
	var resourceIds = [] ;
	var permitIds = [];
	if(dgRows.length > 0) {
		$.each(dgRows, function(i, p){
			var permitAttrIds = [];
			var permitsSpan = $("#subPermitId-"+p.id+"").children("span");
			$.each(permitsSpan, function() {
				permitAttrIds.push($(this).attr("id"));
			});
			
			resourceIds.push(p.id) ;
			permitIds.push(permitAttrIds.join(",")) ;
		});
	}
	
	var data = {"roleId": "${roleId!}", "resourceIds": resourceIds.join(","), "permitIds": permitIds.join("|")};
	
	$.post("${ctx}/manager/system/role/role_resource_add", data, function(result) {
		if (result.status) {
			alertify.success(result.message);$.easyui.loaded();
			if(flag==undefined||flag==false){$d.dialog("close") ;}
		} else {
			$.easyui.loaded();$.messager.alert("错误", result.message, "error");
		}
	}, 'json').error(function() { $.easyui.loaded(); });
};

//验证表单
var submitForm = function($d, $dg, flag) { 
	if($('#form').form('validate')) {
		$.easyui.loading({ msg: "数据提交中，请稍等..." });
		submitNow($d, $dg, flag) ;
	}
};

</script>

